<template>
  <basic-container v-if="show === 'list'">
    <avue-crud
      ref="crud"
      :table-loading="tableLoading"
      :data="tableData"
      :option="tableOption"
      :page.sync="page"
      @on-load="onLoad"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="onLoad"
      @row-del="deleteJob"
    >
      <template slot="td_state" slot-scope="{row}">
        <el-tag effect="dark" :type="row.td_state_type">{{row.td_state}}</el-tag>
      </template>
      <template slot-scope="{type,size , row}" slot="menu">
        <el-button icon="el-icon-view" :size="size" :type="type" @click="viewJobInstances(row)">查看</el-button>
        <el-button icon="el-icon-s-data" :size="size" :type="type">Metric</el-button>
        <el-button v-if="row.td_state === 'PAUSED'" icon="el-icon-caret-right" :size="size" :type="type" @click="action('start' , row)">启动</el-button>
        <el-button v-if="row.td_state === 'NORMAL'" icon="el-icon-remove" :size="size" :type="type" @click="action('stop' , row)">暂停</el-button>
        <el-button v-if="row.td_state === 'PAUSED'" icon="el-icon-caret-right" :size="size" :type="type" @click="action('trigger' , row)">立即触发</el-button>
      </template>
      <template slot-scope="scope" slot="menuLeft">
        <el-button type="primary" icon="el-icon-plus" size="small" @click.stop="show = 'add'">新增</el-button>
      </template>
    </avue-crud>


    <el-dialog append-to-body title="执行记录" :visible.sync="dialogJobInstancesVisible">
      <el-table :height="400" :data="JobInstancesData" v-loading="dialogJobInstancesLoading">
        <el-table-column property="appId" label="AppID" width="150"></el-table-column>
        <el-table-column property="timeStr" label="时间" width="200"></el-table-column>
        <el-table-column property="state" label="状态"></el-table-column>
      </el-table>
    </el-dialog>


  </basic-container>
  <create-job v-else-if="show ==='add'"></create-job>
</template>
<script>

import { griffinService } from '@/api/griffin'
import { dateFormat } from '@/util/date';

import createJob from './create-job';

export default {
  components: {
    'create-job': createJob
  },
  data(){
    return {
      show: 'list',
      tableLoading: false,
      dialogJobInstancesVisible: false,
      dialogJobInstancesLoading: false,
      JobInstancesData: [],
      tableData: [],
      tableOption: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: false,
        editBtn: false,
        addBtn: false,
        menuWidth: 350,
        dialogClickModal: false,
        column: [
          {
            label: '名称',
            prop: 'td_name',
            span: 24
          },
          {
            label: '上次执行时间',
            prop: 'td_previousFireTime',
            format: 'yyyy-MM-dd HH:mm:ss',
            type: 'time',
            value: ''
          },
          {
            label: '下次执行时间',
            prop: 'td_nextFireTime',
            format: 'yyyy-MM-dd HH:mm:ss',
            type: 'time',
            value: ''
          },
          {
            label: '状态',
            prop: 'td_state',
            dicData: [
              {
                label: '暂停',
                value: 'PAUSED'
              },
              {
                label: '正常',
                value: 'NORMAL'
              }
            ]
          }
        ]
      },
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
    }
  },
  mounted(){

  },
  methods: {
    onLoad(){
      this.tableLoading = true;
      griffinService.getJobsList({
        projectId: this.$store.state.dag.projectId
      }).then(
        res => {
          this.tableLoading = false;
          let data = res.data.data;
          let tableData = [];
          let stateType = {
            'PAUSED': 'danger',
            'NORMAL': 'success'
          }
          if(data){
            data.forEach(
              item => {
                tableData.push({
                  ...item,
                  td_name: item['job.name'],
                  td_nextFireTime: item['job.state']['nextFireTime'] !== -1 ? item['job.state']['nextFireTime'] : null,
                  td_previousFireTime: item['job.state']['previousFireTime'] !== -1 ? item['job.state']['previousFireTime'] : null,
                  td_state: item['job.state']['state'],
                  td_state_type: stateType[item['job.state']['state']]
                })
              }
            )
          }
          this.page.total = res.data.totalCounts;
          this.tableData = tableData.sort((a , b) => a.td_previousFireTime < b.td_previousFireTime ? 1 : -1);
        }
      ).catch(() => {
        this.tableData = [];
        this.tableLoading = false;
      })
    },
    handleAdd(){
      
    },
    action(actionName , row){
      let actionNames = {
        'stop': '停止',
        'start': '启动',
        'trigger': '立即触发'
      }
      this.$confirm(`确定要${actionNames[actionName]} ${row.td_name}？` , `${actionNames[actionName]}任务` , {
        beforeClose: (action , instance , done) => {
          if(action === 'confirm'){
            instance.confirmButtonLoading = true;
            griffinService.actionJob(row.id , {
              action: actionName
            }).then(
              () => {
                instance.confirmButtonLoading = false;
                this.$message({
                  type: 'success',
                  message: '操作成功'
                });
                this.onLoad();
                done();
              }
            ).catch(() => {
              instance.confirmButtonLoading = false;
              done();
            })
          }else{
            done();
          }
        }
      });
    },
    deleteJob(row){
      this.$confirm(`确定要删除${row.td_name}？` , `删除任务` , {
        beforeClose: (action , instance , done) => {
          if(action === 'confirm'){
            instance.confirmButtonLoading = true;
            griffinService.deleteJob(row.id).then(
              () => {
                instance.confirmButtonLoading = false;
                this.$message({
                  type: 'success',
                  message: '操作成功'
                });
                this.onLoad();
                done();
              }
            ).catch(() => {
              instance.confirmButtonLoading = false;
              done();
            })
          }else{
            done();
          }
        }
      });
    },
    viewJobInstances(row){
      this.dialogJobInstancesVisible = true;
      this.dialogJobInstancesLoading = true;
      let stateNames = {
        'STARTING': 'STARTING',
        'FOUND': 'FOUND'
      }
      griffinService.getJobInstances({
        jobId: row.id,
        page: 0,
        size: 200
      }).then(
        res => {
          let JobInstancesData = res.data || [];

          JobInstancesData.forEach(
            item => {
              item['timeStr'] = dateFormat(new Date(item['timestamp']));
              item['state'] = stateNames[item['state']] || item['state'];
            }
          )
          this.JobInstancesData = JobInstancesData;
          this.dialogJobInstancesLoading = false;
        }
      ).catch(() => {
        this.dialogJobInstancesLoading = false;
        this.JobInstancesData = [];
      })
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    }
  }
}
</script>